package com.matt.service.courseV2.impl;


import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.page.PagerQuery;
import com.matt.domain.Children;
import com.matt.domain.Classes;
import com.matt.domain.courseV2.GrowthObservation;
import com.matt.domain.courseV2.GrowthObservationRecord;
import com.matt.domain.courseV2.po.GrowthObservationCountPO;
import com.matt.domain.courseV2.po.GrowthObservationRecordAllPO;
import com.matt.domain.courseV2.po.GrowthObservationRecordPO;
import com.matt.domain.courseV2.po.MilepostV2PO;
import com.matt.domain.courseV2.vo.GrowthObservationRecordVO;
import com.matt.foundation.constant.FeedsConstant;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.CopyUtils;
import com.matt.foundation.utils.DateUtil;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.base.BaseNativeSqlRepository;
import com.matt.repository.courseV2.GrowthObservationRecordRepository;
import com.matt.repository.courseV2.GrowthObservationRepository;
import com.matt.service.FeedsService;
import com.matt.service.courseV2.GrowthObservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service
public class GrowthObservationServiceImpl implements GrowthObservationService {




    @Autowired
    protected MemVerificationCache cache;

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private GrowthObservationRepository growthObservationRepository;

    @Autowired
    private GrowthObservationRecordRepository growthObservationRecordRepository;

    @Autowired
    private BaseNativeSqlRepository baseNativeSqlRepository;

    @Autowired
    private FeedsService feedsService;

    @Autowired
    private ClassesRepository classesRepository;

    @Override
    public GrowthObservationRecord getId(String id) {
        return growthObservationRecordRepository.getOne(id);
    }

    @Override
    public GrowthObservationRecord update(String id,String url) {
        GrowthObservationRecord growthObservationRecord =  growthObservationRecordRepository.getOne(id);
        if (Objects.nonNull(growthObservationRecord)){
            growthObservationRecord.setUrl(url);
            growthObservationRecordRepository.save(growthObservationRecord);
        }
        return growthObservationRecord;
    }

    @Override
    public GrowthObservation getMonthAgeGrowth(Integer monthAge) {
        return growthObservationRepository.findByMonthAge(monthAge);
    }

    @Override
    public Page<GrowthObservationCountPO> getGrowthList(String areaId, String classId, String name, PagerQuery pagerQuery) {
        String sql = "SELECT c.id,c.name,cs.id as classId,IFNULL(cs.`name` ,'') as className,COUNT(gr.id) FROM `children` c  LEFT  JOIN rel_classes_children  rc  on rc.childrenId  = c.id  " +
                " LEFT JOIN classes cs  on rc.classesId = cs.id LEFT JOIN tc_growth_record gr on c.id =gr.childrenId    ";

        sql += String.format(" where  cs.areaId  ='%s' ", areaId);


        if (Objects.nonNull(name)) {
            sql += String.format(" and c.name like concat('%s', '%s', '%s') ", "%", name, "%");
        }

        if (Objects.nonNull(classId)){
            sql += String.format("  and cs.id = '%s' ", classId);
        }

        sql += String.format(" GROUP BY c.id ");

        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql);

        sql += String.format("  limit %s, %s ", pagerQuery.getPageNum() * pagerQuery.getPageSize() ,  pagerQuery.getPageSize());

        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);

        List<GrowthObservationCountPO> list  = new ArrayList<>();
        for (int j = 0; j < objects.size(); j++) {
            GrowthObservationCountPO g = new GrowthObservationCountPO();
            g.setChildrenId(objects.get(j)[0].toString());
            g.setChildrenName(objects.get(j)[1].toString());
            g.setClassesId(objects.get(j)[2].toString());
            g.setClassName(objects.get(j)[3].toString());
            g.setContentCount(Integer.valueOf(objects.get(j)[4].toString()));
            g.setLabelCount(Integer.valueOf(objects.get(j)[4].toString()));
            list.add(g);
        }

        return  new PageImpl<>(list, PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize()), objects1.size());
    }

    @Override
    public Page<GrowthObservationRecordVO> getGrowthChildrenList(String childrenId,String classId,Integer monthAge, String states, PagerQuery pagerQuery) {
        Children children = childrenRepository.getOne(childrenId);
        if (Objects.isNull(children)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "学生不存在");
        }
        String sql = "SELECT gr.id,gr.created,gr.cardStates,IFNULL(gr.cardUrl,'') as cardUrl,gr.childrenId,gr.childrenMonthAge " +
                ",gr.classesId,gr.content,gr.label,IFNULL(gr.monthAge,0) as monthAge ,gr.states,IFNULL(gr.url,'') url ," +
                "c.`name` as childrenName,cc.`name` as className,IFNULL(gr.createdBy,'') createdBy " +
                "  FROM `tc_growth_record`  gr  INNER JOIN children c  on  c.id =  gr.childrenId " +
                "INNER JOIN classes cc on cc.id  = gr.classesId  where gr.childrenId = '"+childrenId+"'  ORDER BY gr.created DESC  ";

        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql);
        sql += String.format("  limit %s, %s ", pagerQuery.getPageNum() * pagerQuery.getPageSize() ,  pagerQuery.getPageSize());

        List<GrowthObservationRecordVO> list = baseNativeSqlRepository.sqlObjectList(sql,GrowthObservationRecordVO.class);

        return new PageImpl<>(list, PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize()), objects1.size());
    }

    @Override
    public GrowthObservationRecord add(GrowthObservationRecordPO growthObservationRecordPO) {

        Children children = childrenRepository.getOne(growthObservationRecordPO.getChildrenId());
        if (Objects.isNull(children)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "对象不存在");
        }
        GrowthObservationRecord   growthObservationRecord = new GrowthObservationRecord();
        if (Objects.nonNull(growthObservationRecordPO.getId())){
            growthObservationRecord = growthObservationRecordRepository.getOne(growthObservationRecordPO.getId());
            if (Objects.isNull(growthObservationRecord)){
                throw  new BusinessException(ErrorCode.IS_TARGET, "记录ID错误");
            }
        }
        if (Objects.isNull(growthObservationRecordPO.getCompleteTime())){
            growthObservationRecordPO.setCompleteTime(DateUtil.formatDateToStr(new Date()));
        }
        CopyUtils.copyProperties(growthObservationRecordPO, growthObservationRecord);
        Date time = DateUtil.getLaskWeekDay(growthObservationRecordPO.getCompleteTime());
        //出生到日期的月与天
        String m = DateUtil.birthdayMonthDay(time,children.getBirthday());

        //出生到日期的月与天
        growthObservationRecord.setChildrenMonthAge(m);
        GrowthObservationRecord  growthObservationRecord1 = growthObservationRecordRepository.findByChildrenIdAndMonthAge(growthObservationRecord.getChildrenId(),growthObservationRecord.getMonthAge());
        if (Objects.nonNull(growthObservationRecord1)){
            growthObservationRecord.setId(growthObservationRecord1.getId());
        }
        growthObservationRecordRepository.save(growthObservationRecord);
        return  growthObservationRecord;
    }

    @Override
    public void addAll(StaffDTO staff ,GrowthObservationRecordAllPO growthObservationRecordPO, String staffId) {
        String[] ids =  growthObservationRecordPO.getChildrenIds().split(",");
        List<Children> childrenList = childrenRepository.findByIdIn(ids);

        String[] ids1 = growthObservationRecordPO.getClassIds().split(",");
        List<Classes> classList = classesRepository.findByIdIn(ids1);
        if (Objects.isNull(classList)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "班级不存在");
        }
        if (Objects.isNull(childrenList)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "对象不存在");
        }
        for (int i = 0; i <childrenList.size() ; i++) {

            GrowthObservationRecord growthObservationRecord = new GrowthObservationRecord();
            if (Objects.isNull(growthObservationRecordPO.getCompleteTime())){
                growthObservationRecordPO.setCompleteTime(DateUtil.formatDateToStr(new Date()));
            }
            CopyUtils.copyProperties(growthObservationRecordPO, growthObservationRecord);
            Date time = DateUtil.getLaskWeekDay(growthObservationRecordPO.getCompleteTime());
            //出生到日期的月与天
            String m = DateUtil.birthdayMonthDay(time,childrenList.get(i).getBirthday());

            growthObservationRecord.setChildrenId(childrenList.get(i).getId());
            growthObservationRecord.setClassesId(ids1[i]);
            //出生到日期的月与天
            growthObservationRecord.setChildrenMonthAge(m);

            growthObservationRecord.setCreatedBy(staffId);
            GrowthObservationRecord  growthObservationRecord1 = growthObservationRecordRepository.findByChildrenIdAndMonthAge(growthObservationRecord.getChildrenId(),growthObservationRecord.getMonthAge());
            if (Objects.nonNull(growthObservationRecord1)){
                growthObservationRecord.setId(growthObservationRecord1.getId());
            }
            growthObservationRecordRepository.save(growthObservationRecord);

            feedsService.save(staff.getId(), childrenList.get(i).getId(), staff.getAreaId(), "", FeedsConstant.GROWTH_OBSERVATION, childrenList.get(i).getName()+"的"+growthObservationRecordPO.getMonthAge()+"月里程碑", "","", "", growthObservationRecord.getId());

        }
    }

    @Override
    public List<MilepostV2PO> getMileageList(String areaId, PagerQuery pagerQuery) {
        String sql = "SELECT gr.id,c.id as cId ,c.`name`,IFNULL(cs.`name` ,'') as className,gr.label ,gr.created , gr.childrenMonthAge ,gr.cardStates  " +
                "FROM `tc_growth_record` gr INNER JOIN children c on gr.childrenId = c.id  INNER JOIN classes cs on gr.classesId = cs.id    ";

        sql += String.format(" where  cs.areaId  ='%s' ", areaId);

        sql += String.format("   limit %s, %s ", pagerQuery.getPageNum() * pagerQuery.getPageSize() ,  pagerQuery.getPageSize());
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);

        List<MilepostV2PO> list  = new ArrayList<>();
        for (int j = 0; j < objects.size(); j++) {
            MilepostV2PO m = new MilepostV2PO();
            m.setId(objects.get(j)[0].toString());
            m.setChildrenId(objects.get(j)[1].toString());
            m.setChildrenName(objects.get(j)[2].toString());
            m.setClassName(objects.get(j)[3].toString());
            m.setContent(objects.get(j)[4].toString());
            m.setCompleteTime(objects.get(j)[5].toString());
            m.setChildrenMonthAge(objects.get(j)[6].toString());
            m.setCardStates(objects.get(j)[7].toString());
            list.add(m);
        }
        return list;
    }
}
